import {Component} from '@angular/core';
import {IonicPage, NavController, NavParams} from 'ionic-angular';
import {ValidateProvider} from "../../providers/validate/validate";
import {HttpServicesProvider} from "../../providers/http-services/http-services";
import {UtilsProvider} from "../../providers/utils/utils";
import {ConfigProvider} from "../../providers/config/config";

@IonicPage({
    segment: 'service/bbs/publish',
    defaultHistory: ['HomePage','ServicePage', 'ServiceBbsPage']
})
@Component({
    selector: 'page-community-edit',
    templateUrl: 'community-edit.html',
})
export class CommunityEditPage {
    postData = {
        token: '',
        type_id: 20,
        auto_content: '',
        cover: [],
        voice: ''
    };
    constructor(
        public navCtrl: NavController,
        public navParams: NavParams,
        public validate: ValidateProvider,
        public httpService: HttpServicesProvider,
        public util: UtilsProvider,
        public config: ConfigProvider
    ) {
    }

    ionViewCanEnter(){
        return this.validate.checkLogin();
    }

    /**
     * 上传图片
     * */
    uploadImage(item, e) {
        let file = e.target.files[0];
        let data = new FormData();
        data.append('image', file);
        data.append('type', 'bbs');
        // data.append('water', 'true');
        // data['water'] = true;
        this.httpService.uploadImage('/user/upload_file', data, result => {
            if(result['code'] == 200){
                this.postData['cover'].push(result['img_path']);
            }
        });
    }

    /**
     * 发布消息
     * */
    publish(){
        let apiUrl = "/service/add_info_handle";
        this.postData.token = this.config.getToken();
        this.httpService.requestPostData(apiUrl, this.postData, result => {
            if(result['error'] == 200){
                this.util.presentAlert('信息发布成功');
                this.navCtrl.popTo('ServiceBbsPage');
            }else{
                this.util.presentAlert('系统有误，发布失败，请稍后再试');
            }
        });
    }

    delImg(img){
        this.util.presentConfirm('确定删除吗？', () => {
            let index = this.util.inArray(this.postData['cover'], img);
            if (index > -1) {
                this.postData['cover'].splice(index, 1);
            }
        });
    }

}
